<template>
    <div class="app-container">
        <el-page-header @back="goBack" :content="'参数设置'" class="page-header">
        </el-page-header>

        <el-tabs v-model="activeTab" type="card" class="setting-tabs">
            <el-tab-pane label="基本设置" name="basic">
                <div class="control-grid">
                    <div v-for="(item, index) in paramList" :key="index" class="control-item" v-loading="item.loading">
                        <div class="item-title">{{ item.title }}</div>
                        <div class="item-content">
                            <div>
                                <!-- 启动 -->
                                <el-button
                                    v-if="item.title === '一键启动'"
                                    type="warning"
                                    size="mini"
                                    @click="handleParamChange(item, '1', index)"
                                    :loading="item.loading"
                                >启动
                                </el-button>

                                <!-- 停止 -->
                                <el-button
                                    v-else-if="item.title === '停止'"
                                    type="warning"
                                    size="mini"
                                    @click="handleParamChange(item, '0', index)"
                                    :loading="item.loading"
                                >停止
                                </el-button>

                                <!-- 碾米次数 -->
                                <div v-else-if="item.title === '碾米次数'">
                                    <div style="text-align: center">
                                        {{ item.value }}
                                    </div>
                                    <el-button
                                        type="primary"
                                        size="mini"
                                        @click="handleReadCount(item, index)"
                                        style="margin-top: 10px"
                                        :loading="item.loading"
                                    >读取
                                    </el-button>
                                </div>

                                <!-- 碾米次数清0 -->
                                <el-button
                                    v-else-if="item.title === '碾米次数清0'"
                                    type="warning"
                                    size="mini"
                                    @click="handleParamChange(item, 0, index)"
                                    :loading="item.loading"
                                >清零
                                </el-button>

                                <!-- 恢复出厂设置按钮 -->
                                <el-button
                                    v-if="item.type === 'button' && item.title === '恢复出厂设置'"
                                    type="warning"
                                    size="mini"
                                    @click="handleParamChange(item, '1', index)"
                                    style="margin-top: 20px"
                                    :loading="item.loading"
                                >恢复出厂设置
                                </el-button>

                                <!-- 模式开关 -->
                                <div style="display: flex;flex-direction: column;justify-content: center"  v-if="item.type === 'switch'">
                                    <el-switch
                                        v-model="item.value"
                                        :active-text="item.title === '时间/物料模式' ? '时间' : '打开'"
                                        :inactive-text="item.title === '时间/物料模式' ? '物料' : '关闭'"
                                        active-value="1"
                                        inactive-value="0"
                                        @change="(val) => handleParamChange(item, val, index)"
                                        style="margin-top: 5px"
                                        :loading="item.loading"
                                    ></el-switch>
                                    <el-button
                                        type="primary"
                                        size="mini"
                                        @click="handleReadCount(item, index)"
                                        style="margin-top: 10px"
                                        :loading="item.loading"
                                    >读取
                                    </el-button>
                                </div>

                                <!-- 输入框 -->
                                <el-input
                                    v-else-if="!item.type && item.title !== '碾米次数' && item.title !== '碾米次数清0'&& item.title !== '一键启动'&& item.title !== '停止'"
                                    v-model="item.value"
                                    clearable
                                    size="small"
                                    placeholder="输入数值"
                                />
                                <!-- 显示单位 -->
                                <div>
                                    <span style="color: #888; font-size: 14px;">{{ item.unit }}</span>
                                </div>
                                <div style="display: flex;justify-content: center;margin-top: 5px">
                                    <!-- 保存按钮：只要不是特殊类型的控件都显示 -->
                                    <el-button
                                        v-if="!item.type && item.title !== '碾米次数' && item.title !== '碾米次数清0' && item.title !== '一键启动' && item.title !== '停止'"
                                        type="primary"
                                        size="mini"
                                        style="margin-left: 8px"
                                        @click="handleParamChange(item, item.value, index)"
                                        :loading="item.loading"
                                    >保存
                                    </el-button>
                                    <el-button
                                        v-if="!item.type && item.title !== '碾米次数'&& item.title !== '碾米次数清0' && item.title !== '一键启动' && item.title !== '停止'"
                                        type="primary"
                                        size="mini"
                                        @click="handleReadCount(item, index)"
                                        :loading="item.loading"
                                    >读取
                                    </el-button>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
            </el-tab-pane>

            <el-tab-pane label="采样设置" name="sampling">
                <el-row :gutter="20">
                    <el-col
                        :xs="8"
                        :sm="8"
                        :md="8"
                        :lg="8"
                        :xl="8"
                        v-for="(item, index) in samplingList"
                        :key="index"
                        style="margin-top: 20px"
                    >
                        <el-card class="box-card" v-loading="item.loading">
                            <div slot="header" class="clearfix">
                                <span style="font-size: 14px; height: 30px; display: inline-block; line-height: 30px">
                                    {{ item.title }}
                                </span>
                            </div>
                            <el-form>
                                <el-form-item>
                                    <el-input
                                        v-model="item.value"
                                        clearable
                                        size="small"
                                    />
                                    <div style="display: flex;flex-direction: column;align-items: center">
                                        <el-button
                                            type="primary"
                                            size="mini"
                                            @click="handleReadCount(item, index)"
                                            :loading="item.loading"
                                        >
                                            读取
                                        </el-button>
                                        <el-button
                                            type="primary"
                                            size="mini"
                                            @click="handleParamChange(item, item.value, index)"
                                            style="margin-right: 8px;margin-top: 8px"
                                            :loading="item.loading"
                                        >
                                            保存
                                        </el-button>
                                    </div>
                                </el-form-item>
                            </el-form>
                        </el-card>
                    </el-col>
                </el-row>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script>
import {
    listInstanceProperty,
    instanceFunctionInvoke, getDeviceProduct
} from '@/api/device/product'
import { genUUID } from '@/utils/ruoyi'

export default {
    name: 'index',
    data() {
        return {
            webClientId: genUUID(),
            productId: '',
            deviceId: '',
            // 产品信息
            productInfo: {},
            // 元数据属性列表
            metadataProperties: [],
            curIndex: null,
            paramList: [
                {
                    title: '一键启动',
                    value: '1',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '停止',
                    value: '0',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '参数设置密码',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '碾米次数',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '碾米次数清0',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '时间/物料模式',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null,
                    type: 'switch'
                },
                // 以下是你截图的六个参数
                {
                    title: '砻谷机报警电流',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '粉碎机报警电流',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '碾米机报警电流',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '时间/物料模式(自动切换)',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null,
                    type: 'switch'
                },
                {
                    title: '砻谷机持续报警时长',
                    value: '',
                    propertyId: null,
                    unit: '秒后，播报警语音',
                    loading: false,
                    timer: null
                },
                {
                    title: '粉碎机持续报警时长',
                    value: '',
                    propertyId: null,
                    unit: '秒后，播报警语音',
                    loading: false,
                    timer: null
                },
                {
                    title: '碾米机持续报警时长',
                    value: '',
                    propertyId: null,
                    unit: '秒后，播报警语音',
                    loading: false,
                    timer: null
                },
                {
                    title: '恢复出厂设置',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null,
                    type: 'button'
                }
            ],
            activeTab: 'basic',
            samplingList: [
                // 第一行
                {
                    title: '谷斗传感器采样时间',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '谷斗传感器采样数量',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '谷斗传感器触发阈值',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                // 第二行
                {
                    title: '重力筛1传感器采样时间',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '重力筛1传感器采样数量',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '重力筛1传感器触发阈值',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                // 第三行
                {
                    title: '重力筛2传感器采样时间',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '重力筛2传感器采样数量',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '重力筛2传感器触发阈值',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                // 第四行
                {
                    title: '白米斗传感器采样时间',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '白米斗传感器采样数量',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '白米斗传感器触发阈值',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                // 第五行
                {
                    title: '白米出口传感器采样时间',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '白米出口传感器采样数量',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '白米出口传感器触发阈值',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                // 第六行
                {
                    title: '一键启动按键采样时间',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '一键启动按键采样数量',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '一键启动按键采样阈值',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                // 第七行
                {
                    title: '全自动/半自动按键采样时间',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '全自动/半自动按键采样数量',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                },
                {
                    title: '全自动/半自动按键采样阈值',
                    value: '',
                    propertyId: null,
                    loading: false,
                    timer: null
                }
            ]
        }
    },
    created() {
        if (this.$route.query && this.$route.query.productId) {
            this.productId = this.$route.query.productId
        }
        if (this.$route.query && this.$route.query.deviceId) {
            this.deviceId = this.$route.query.deviceId
        }
        this.handleViewProduct()
    },
    methods: {
        goBack() {
            this.$router.push('/equipment/riceHuskingMachine')
        },
        // 查看产品详情
        handleViewProduct() {
            getDeviceProduct(this.productId).then(response => {
                this.productInfo = response.data
                // 解析metadata
                if (this.productInfo.metadata) {
                    try {
                        const metadata = JSON.parse(this.productInfo.metadata)
                        // 创建名称到属性的映射
                        const metadataMap = {}
                        metadata.properties.forEach(prop => {
                            if (prop.name === '时间模式/感应模式') {
                                prop.name = '时间/物料模式'
                            }
                            if (prop.name === '时间模式/感应模式控制') {
                                prop.name = '时间/物料模式(自动切换)'
                            }
                            if (prop.name === '加工次数') {
                                prop.name = '碾米次数'
                            }
                            metadataMap[prop.name] = prop
                        })
                        // console.log('metadataMap', metadataMap)

                        let startPropertyId = null
                        let countPropertyId = null

                        // 单次循环处理所有情况
                        this.paramList.forEach(item => {
                            if (item.title === '一键启动') {
                                const metaProp = metadataMap[item.title]
                                if (metaProp) {
                                    startPropertyId = metaProp.id
                                    item.propertyId = startPropertyId
                                }
                            } else if (item.title === '碾米次数') {
                                const metaProp = metadataMap[item.title]
                                if (metaProp) {
                                    countPropertyId = metaProp.id
                                    item.propertyId = countPropertyId
                                }
                            } else if (item.title === '停止') {
                                item.propertyId = startPropertyId
                            } else if (item.title === '碾米次数清0') {
                                item.propertyId = countPropertyId
                            } else {
                                const metaProp = metadataMap[item.title]
                                if (metaProp) {
                                    item.propertyId = metaProp.id
                                }
                            }
                        })
                        this.samplingList.forEach(item => {
                            const metaProp = metadataMap[item.title]
                            if (metaProp) {
                                item.propertyId = metaProp.id
                            }
                        })

                        // 保存metadata属性以供后续使用
                        this.metadataProperties = metadata.properties || []

                        // console.log('Updated paramList:', this.paramList)
                        // console.log('Updated samplingList:', this.samplingList)
                        this.listInstancePropertyData()
                    } catch (e) {
                        console.error('解析metadata失败:', e)
                        this.metadataProperties = []
                    }
                }
            })
        },

        listInstancePropertyData() {
            let obj = {
                deviceId: this.deviceId
            }
            listInstanceProperty(obj).then(res => {
                // 先转成 propertyId -> propertyFormatValue 的 map
                const propertyMap = res.data.reduce((acc, item) => {
                    acc[item.propertyId] = item.propertyFormatValue
                    return acc
                }, {})
                // 遍历 paramList，赋值
                this.paramList.forEach(item => {
                    if (propertyMap.hasOwnProperty(item.propertyId)) {
                        item.value = propertyMap[item.propertyId]
                    } else {
                        item.value = null // 或者保留原始值
                    }
                })
                this.samplingList.forEach(item => {
                    if (propertyMap.hasOwnProperty(item.propertyId)) {
                        item.value = propertyMap[item.propertyId]
                    } else {
                        item.value = null // 或者保留原始值
                    }
                })
            })
        },
        async handleParamChange(item, val, index) {
            this.curIndex = index
            if (item.title === '碾米次数') return
            let value = item.title === '碾米次数清0' ? 0 : val

            item.value = value
            this.getTimer(index)
            this.paramList[index].loading = true
            try {
                const res = await instanceFunctionInvoke({
                    productId: this.productId,
                    deviceId: this.deviceId,
                    functionId: 'modbus-write10',
                    data: {
                        id: item.propertyId,
                        value: value.toString()
                    },
                    clientId: this.webClientId
                })
                // console.log('res', res)
                if (res.data) {
                    let obj = {
                        'webClientId': this.webClientId,
                        'type': 'login'
                    }
                    this.sendMessage(obj)
                }
                if (item.title === '碾米次数清0') {
                    let countItem = this.paramList.find(i => i.title === '碾米次数')
                    if (countItem) countItem.value = 0
                }
            } catch (e) {
                this.$message.error('操作失败')
                this.paramList[index].loading = false
            }
        },
        async handleReadCount(item, index) {
            console.log(item)
            console.log(index)
            this.curIndex = index
            item.loading = true
            this.getTimer(index)
            try {
                const res = await instanceFunctionInvoke({
                    productId: this.productId,
                    deviceId: this.deviceId,
                    functionId: 'modbus-read03',
                    data: {
                        id: item.propertyId
                    },
                    clientId: this.webClientId
                })
                if (res.data) {
                    let obj = {
                        'webClientId': this.webClientId,
                        'type': 'login'
                    }
                    this.sendMessage(obj)
                }
            } catch (e) {
                this.$message.error('读取失败')
                item.loading = false
            }
        },
        getTimer(index) {
            let loadingTime = 30
            let that = this
            if (this.activeTab === 'sampling') {
                this.samplingList[index].timer = setInterval(() => {
                    if (loadingTime <= 0) {
                        that.resetTime(index)
                    } else {
                        // loadingText.value = loadingTime+ 's'
                        --loadingTime
                    }
                }, 1000)
            } else {
                this.paramList[index].timer = setInterval(() => {
                    if (loadingTime <= 0) {
                        that.resetTime(index)
                    } else {
                        // loadingText.value = loadingTime+ 's'
                        --loadingTime
                    }
                }, 1000)
            }
        },
        // 重置
        resetTime(index) {
            // 根据propertyId找到对应的流程步骤
            this.paramList[index].loading = false
            clearInterval(this.paramList[index].timer)
            clearInterval(this.samplingList[index].timer)
            this.$message.error('系统繁忙，请稍后再试')
        },
        // websocket 发送消息给服务器
        sendMessage(obj) {
            if (this.ws !== undefined && this.ws.readyState === 1) {
                console.log('exist')
                // this.$websocket.sendMsg(obj)
            } else {
                this.localSocket(obj)
            }
        },
        localSocket(obj) {
            let that = this
            if ('WebSocket' in window) {
                console.log('您的浏览器支持 WebSocket')
                // console.log('that.ws', that.ws)
                if (that.ws !== undefined && that.ws.readyState === 1) {
                    console.log('exist')
                    return
                }

                that.ws = new WebSocket(that.$websocket.url)
                that.$websocket.setWs(that.ws)
                that.ws.onopen = function() {
                    console.log('开始连接')
                    // that.sendMessage(obj)
                    that.$websocket.sendMsg(obj)
                }
                // websocket 接收服务器消息
                that.ws.onmessage = function(result) {
                    console.log('收到websocket回复', result)
                    // console.log('回复data', result.data)
                    that.processData(result.data)
                }
                that.ws.onclose = function() {
                    // 防链接超时，（websocket在一定时间内没有数据交互，就会断开），关闭后重启
                    console.log('连接已关闭')
                    that.ws.close()
                }
            } else {
                // 浏览器不支持 WebSocket
                console.log('您的浏览器不支持 WebSocket!')
            }
        },
        processData(json) {
            console.log('json', json)
            if (json === 'ok') {
                console.log('WebSocket连接成功')
                return
            }

            let data = {}
            try {
                data = JSON.parse(json)
                console.log('data', data)
                // 检查是否包含必要的字段
                if (data.webClientId && data.id && data.value !== undefined) {
                    // 根据id找到对应的流程步骤
                    let foundStep = null
                    let flowArray = []
                    if (this.activeTab === 'sampling') {
                        flowArray = this.samplingList
                    } else {
                        flowArray = this.paramList
                    }
                    foundStep = flowArray[this.curIndex]
                    foundStep.loading = false
                    clearInterval(foundStep.timer)
                    foundStep.value = data.value
                    this.$message.success('保存成功')
                }
            } catch (e) {
                console.error('解析数据失败:', e)
            }
        }
    }
}
</script>

<style scoped lang="scss">
.control-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    justify-content: center;
    padding: 10px;
    background-color: #fff;
    border-radius: 4px;
}

.control-item {
    width: 48%;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    background-color: #fff;

    .item-title {
        font-size: 14px;
        color: #606266;
        text-align: center;
        margin-bottom: 10px;
        font-weight: 500;
    }

    .item-content {
        display: flex;
        gap: 8px;
        align-items: center;
        justify-content: center;

        .el-button {
            flex-shrink: 0;
        }
    }
}

.box-card {
    height: 240px;
}

.page-header {
    margin-bottom: 24px;
    padding: 18px 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 24px 0 rgba(0, 0, 0, .08);
}

.setting-tabs {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 24px 0 rgba(0, 0, 0, .08);
}

.page-header ::v-deep(.el-page-header__title) {
    font-size: 16px;
    font-weight: bold;
}

.page-header ::v-deep(.el-page-header__content) {
    font-size: 16px;
}

@media (max-width: 600px) {
    .page-header {
        padding: 12px;
        margin-bottom: 15px;
    }

    .page-header ::v-deep(.el-page-header__title) {
        font-size: 14px;
    }

    .page-header ::v-deep(.el-page-header__content) {
        font-size: 14px;
    }

    .setting-tabs {
        padding: 10px;
    }
}

/* 确保一行显示两个卡片 */
.app-container ::v-deep(.el-row) {
    display: flex;
    flex-wrap: wrap;
}

/* 基本设置tab中的卡片布局 */
.app-container ::v-deep(.el-tab-pane[name="basic"] .el-col) {
    flex: 0 0 50%;
    max-width: 50%;
}

/* 采样设置tab中的卡片布局 */
.app-container ::v-deep(.el-tab-pane[name="sampling"] .el-col) {
    flex: 0 0 33.333333%;
    max-width: 33.333333%;
}

.el-input {
    margin-bottom: 10px;
}

/* 移除卡片内容区域的内边距 */
::v-deep .el-card__body {
    padding: 5px;
}

</style>
